package cn.yangliu.config.custom;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * @author 杨柳
 * @date 2019-05-31
 */
@Component
public class AuthenticationProviderImpl implements AuthenticationProvider {
    /**
     * 模拟缓存
     */
    private Map<String,Authentication> authenticationMap = new HashMap<>();
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        Authentication token = authenticationMap.get(username);
        if (Objects.nonNull(token)){
            return token;
        }

        String password = authentication.getCredentials().toString();

        UserDetails userDetails = new UserDetails() {
            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                Set<GrantedAuthority> set = new HashSet<>();
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_admin");
                set.add(authority);
                return set;
            }

            @Override
            public String getPassword() {
                return password;
            }

            @Override
            public String getUsername() {
                return username;
            }

            @Override
            public boolean isAccountNonExpired() {
                return true;
            }

            @Override
            public boolean isAccountNonLocked() {
                return true;
            }

            @Override
            public boolean isCredentialsNonExpired() {
                return true;
            }

            @Override
            public boolean isEnabled() {
                return true;
            }
        };
        token = new UsernamePasswordAuthenticationToken(userDetails,password,userDetails.getAuthorities());
        authenticationMap.put(username,token);
        return token;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
